package com.kerrykidz.sales.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.ORDER_CONSTANTS;
import com.kerrykidz.dao.model.GblPosDiscountEntity;
import com.kerrykidz.sales.dao.model.OrderRecord;
import com.kerrykidz.sales.dao.model.PosOrderEntity;
import com.kerrykidz.sales.dao.model.PosOrderPaymentEntity;
import com.kerrykidz.sales.dao.model.PosOrderPrdEntity;
import com.kerrykidz.sales.service.IDiscountService;
import com.kerrykidz.sales.service.IOrderService;
import com.kerrykidz.sales.service.IPaymentService;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.dao.model.ScmPrdStgEntity;
import com.kerrykidz.scminvoicing.service.IScmInvocingProductInfoService;
import com.kerrykidz.scmstock.service.IStockGoodsInService;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;

/**
 * 
 * @Description 订单相关操作
 * @author QUINN
 * @date 2014年8月21日下午1:28:25
 */
@Controller
@RequestMapping("order")
public class OrderController {

	@Autowired
	private IPaymentService paymentService;

	@Autowired
	private IOrderService orderService;

	@Autowired
	private IDiscountService discountService;

	@Autowired
	private IScmInvocingProductInfoService scmInvocingProductInfoService;

	@Autowired
	private IStockGoodsInService stockGoodsInService;

	// 退货页面
	@RequestMapping(value = "refund", method = RequestMethod.GET)
	public String refundGet(@RequestParam("id") String id, ModelMap model) {
		PosOrderEntity order = this.orderService.findOrderByPk(id);
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		try {
			List<OrderRecord> records = this.orderService.findOrderRecord(id);
			model.put("records", records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("order", order);
		model.put("products", products);
		return "goods/refund";
	}

	// 购物车页面
	@RequestMapping(value = "shopCart")
	public String shopCart(String id, Boolean isParty, ModelMap model, HttpSession session) throws Exception {

		if (isParty == null)
			isParty = (Boolean) session.getAttribute("isParty");

		if (isParty != null && isParty) {
			id = (String) session.getAttribute("shopCartId");
		} else {
			if (StringUtils.isBlank(id))
				id = this.getFromSession(session);
		}

		session.setAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID, id);

		PosOrderEntity order = this.orderService.findOrderByPk(id);
		session.setAttribute("isParty", ORDER_CONSTANTS.ORDER_TYPE_PARTY.equals(order.getOrderType()));
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		List<GblPosDiscountEntity> discounts = this.scmInvocingProductInfoService.findAllDiscount();
		model.put("order", order);
		model.put("products", products);
		model.put("discounts", discounts);
		return "goods/shopCart";
	}

	// 获取商品数量
	@RequestMapping(value = "getProductCount", method = RequestMethod.POST)
	@ResponseBody
	public int getProductCount(@RequestParam("productId") String productId) throws RDPException {
		GblScmPrdEntity prd = this.scmInvocingProductInfoService.getProductById(productId, UserUtil
				.getUserFromSession().getBranId());
		return prd.getStgCnt() == null ? 0 : prd.getStgCnt();
	}

	public String getFromSession(HttpSession session) {
		UserInfo user = UserUtil.getUserFromSession();

		String id = (String) session.getAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);

		if (StringUtils.isBlank(id)) {

			// 查找最近的一购物车
			PosOrderEntity order = new PosOrderEntity();
			order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_SHOPCART);
			String userid = user.getUserId();
			order.setFkOperator(userid);
			order = this.orderService.findByCondition(order);
			if (order == null)
				order = this.orderService.createAndfindCurrentShopCart(user.getUserId(), user.getAbbrCode(),
						user.getBranId());
			id = order.getPkOrderId();
		}
		return id;
	}

	// 订单列表页面
	@RequestMapping(value = "list")
	public String list() {
		return "goods/order_list";
	}

	// 分页查询订单信息
	@RequestMapping(value = "paginate", method = RequestMethod.POST)
	@ResponseBody
	public PosOrderEntity paginate(PosOrderEntity order, Boolean onlyMe) {
		if (onlyMe != null && onlyMe) {
			UserInfo user = UserUtil.getUserFromSession();
			order.setFkOperator(user.getUserId());
		}
		this.orderService.paginate(order);
		return order;
	}

	@RequestMapping(value = "detail")
	public String detail(ModelMap model, @RequestParam("id") String id) {
		PosOrderEntity order = this.orderService.findOrderByPk(id);
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		List<OrderRecord> records = new ArrayList<OrderRecord>();
		try {
			List<PosOrderPaymentEntity> payments = this.paymentService.findByOrderPk(id);
			for (PosOrderPaymentEntity payment : payments) {
				records.add(new OrderRecord(payment));
			}
			model.put("records", records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("order", order);
		model.put("products", products);
		return "goods/order_detail";
	}

	@RequestMapping(value = "detail2")
	public String detail2(ModelMap model, @RequestParam("id") String id) {
		PosOrderEntity order = this.orderService.findOrderByPk(id);
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		List<OrderRecord> records = new ArrayList<OrderRecord>();
		try {
			List<PosOrderPaymentEntity> payments = this.paymentService.findByOrderPk(id);
			for (PosOrderPaymentEntity payment : payments) {
				records.add(new OrderRecord(payment));
			}
			model.put("records", records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("order", order);
		model.put("products", products);
		return "goods/order_detail_2";
	}

	@RequestMapping(value = "updateOrder", method = RequestMethod.POST)
	public String updateOrder(PosOrderEntity order, @RequestParam("values") String[] values, HttpSession session) {

		List<PosOrderPrdEntity> products = new ArrayList<PosOrderPrdEntity>();

		/*
		 * 先解析字符串转为PosOrderPrdEntity
		 */

		UserInfo user = UserUtil.getUserFromSession();

		for (String pstrs : values) {

			PosOrderPrdEntity prd = new PosOrderPrdEntity();

			String pstr[] = pstrs.split("_");

			// =4表示有备注
			boolean hasRemark = pstr.length == 4;

			prd.setPkOrderId(order.getPkOrderId());
			prd.setType(ORDER_CONSTANTS.ORDER_PRD_TYPE_PRODUCT);
			prd.setFkPrdId(pstr[0]);
			prd.setCount(Integer.valueOf(pstr[1]));
			if (hasRemark)
				prd.setDiscComments(pstr[3]);
			if (StringUtils.isNotBlank(order.getFkDisId()))
				prd.setFkDisId(order.getFkDisId());
			else if (StringUtils.isNotBlank(pstr[2]) && !"0".equals(pstr[2])) {
				prd.setFkDisId(pstr[2]);
			}

			try {
				GblScmPrdEntity p = this.scmInvocingProductInfoService.getProductById(pstr[0], user.getBranId());
				prd.setPrice(p.getProductPrice());
				if (prd.getFkDisId() != null) {
					GblPosDiscountEntity dis = this.discountService.findDiscountByPk(prd.getFkDisId());
					prd.setDisPrice(prd.getPrice() * dis.getDisValue() * prd.getCount());
				} else {
					prd.setDisPrice(prd.getPrice() * prd.getCount());
				}
			} catch (RDPException e) {
				e.printStackTrace();
			}

			products.add(prd);

		}

		/*
		 * 更改订单信息
		 */

		order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_NOT_PAY);

		order.setModiBy(user.getUserId());
		order.setModiTime(new Date());
		try {
			this.orderService.updateOrder(order, products);
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.removeAttribute("shopCartId");
		session.removeAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);
		return "redirect:/order/list.shtml";
	}

	@RequestMapping(value = "getOrderId", method = RequestMethod.POST)
	@ResponseBody
	public String getOrderId(@RequestParam("pdId") String pdId) {
		PosOrderEntity order = new PosOrderEntity();
		// 根据排队查找订单
		order.setFkParresId(pdId);
		order = this.orderService.findByCondition(order);
		return order.getPkOrderId();
	}

	@RequestMapping(value = "cancelOrder")
	public String cancelOrder(@RequestParam("id") String id, HttpSession session) {
		PosOrderEntity order = new PosOrderEntity();
		order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_CANCEL);
		order.setPkOrderId(id);
		this.orderService.updateOrder(order);
		session.removeAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);

		this.updateStg(id);

		return "redirect:/payment/skmx.shtml";
	}

	private void updateStg(String id) {
		List<PosOrderPrdEntity> list = this.orderService.findOrderPrdByOrderId(id);

		if (list != null) {
			for (PosOrderPrdEntity prd : list) {
				if (ORDER_CONSTANTS.ORDER_PRD_TYPE_PRODUCT.equals(prd.getType())) {
					ScmPrdStgEntity scmPrdStg = new ScmPrdStgEntity();
					scmPrdStg.setInstgCnt(prd.getCount());
					scmPrdStg.setFkPrdId(prd.getFkPrdId());
					scmPrdStg.setFkBranId(UserUtil.getUserFromSession().getBranId());

					try {
						this.stockGoodsInService.updateScmPrdStg(scmPrdStg);
					} catch (RDPException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@RequestMapping(value = "cancelOrderAjax")
	@ResponseBody
	public boolean cancelOrderAjax(@RequestParam("id") String id) {
		PosOrderEntity order = new PosOrderEntity();
		order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_CANCEL);
		order.setPkOrderId(id);
		this.orderService.updateOrder(order);
		this.updateStg(id);
		return true;
	}

	// pad端的购物车页面
	@RequestMapping(value = "shopCartForPad")
	@ResponseBody
	public HashMap<String, Object> shopCartForPad(@RequestParam("shopCartId") String id, HttpSession session)
			throws Exception {
		if (StringUtils.isBlank(id))
			id = this.getFromSession(session);
		session.setAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID, id);
		PosOrderEntity order = this.orderService.findOrderByPk(id);
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("order", order);
		result.put("products", products);
		result.put("loginUser", UserUtil.getUserFromSession());
		return result;
	}

	/**
	 * pad端查询订单的详细信息
	 * 
	 * @author ScreenJxp
	 * @param entity
	 * @return
	 * @date: 2014年11月6日
	 */
	@RequestMapping("/findOrderList")
	@ResponseBody
	public List<PosOrderEntity> findOrderList(PosOrderEntity entity) {
		entity.setIspaging(true);
		return orderService.findOrderList(entity);
	}

	/**
	 * pad 端修改订单的状态
	 * 
	 * @param order
	 * @param values
	 * @param session
	 * @return
	 * @date: 2014年11月7日
	 */
	@RequestMapping(value = "updateOrderForPad", method = RequestMethod.POST)
	@ResponseBody
	public String updateOrderForPad(PosOrderEntity order, @RequestParam("values") String[] values, HttpSession session) {

		List<PosOrderPrdEntity> products = new ArrayList<PosOrderPrdEntity>();

		/*
		 * 先解析字符串转为PosOrderPrdEntity
		 */

		UserInfo user = UserUtil.getUserFromSession();

		for (String pstrs : values) {

			PosOrderPrdEntity prd = new PosOrderPrdEntity();

			String pstr[] = pstrs.split("_");

			// =4表示有备注
			boolean hasRemark = pstr.length == 4;

			prd.setPkOrderId(order.getPkOrderId());
			prd.setType(ORDER_CONSTANTS.ORDER_PRD_TYPE_PRODUCT);
			prd.setFkPrdId(pstr[0]);
			prd.setCount(Integer.valueOf(pstr[1]));
			if (hasRemark)
				prd.setDiscComments(pstr[3]);
			if (StringUtils.isNotBlank(order.getFkDisId()))
				prd.setFkDisId(order.getFkDisId());
			else if (StringUtils.isNotBlank(pstr[2]) && !"0".equals(pstr[2])) {
				prd.setFkDisId(pstr[2]);
			}

			try {
				GblScmPrdEntity p = this.scmInvocingProductInfoService.getProductById(pstr[0], user.getBranId());
				prd.setPrice(p.getProductPrice());
				if (prd.getFkDisId() != null) {
					GblPosDiscountEntity dis = this.discountService.findDiscountByPk(prd.getFkDisId());
					prd.setDisPrice(prd.getPrice() * dis.getDisValue() * prd.getCount());
				} else {
					prd.setDisPrice(prd.getPrice() * prd.getCount());
				}
			} catch (RDPException e) {
				e.printStackTrace();
			}

			products.add(prd);

		}

		/*
		 * 更改订单信息
		 */

		order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_NOT_PAY);

		order.setModiBy(user.getUserId());
		order.setModiTime(new Date());
		try {
			this.orderService.updateOrder(order, products);
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.removeAttribute(ORDER_CONSTANTS.CURRENT_ORDER_ID);
		return Constants.SUCCESS;
	}

	/***
	 * pad端订单的详细信息
	 * 
	 * @author ScreenJxp
	 * @param model
	 * @param id
	 * @return
	 * @date: 2014年11月7日
	 */
	@RequestMapping(value = "orderDetailForPad")
	public String orderDetailForPad(ModelMap model, @RequestParam("id") String id) {
		PosOrderEntity order = this.orderService.findOrderByPk(id);
		List<PosOrderPrdEntity> products = this.orderService.findOrderPrdByOrderId(id);
		List<OrderRecord> records = new ArrayList<OrderRecord>();
		try {
			List<PosOrderPaymentEntity> payments = this.paymentService.findByOrderPk(id);
			for (PosOrderPaymentEntity payment : payments) {
				records.add(new OrderRecord(payment));
			}
			model.put("records", records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("order", order);
		model.put("products", products);
		return "goods/order_detailForPad";
	}

	/***
	 * 打印收银的明细
	 * 
	 * @author ScreenJxp
	 * @return
	 * @date: 2014年11月24日
	 */
	@RequestMapping("/printOrderDetail")
	public void printOrderDetail(@Param("pkOrderId") String pkOrderId) {
		this.orderService.printOrderDetail(pkOrderId);
	}
}
